<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Upload;

/**
 * Awaiting控制器
 */
class Awaiting extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Purchase();

        $this->validate = \app\admin\validate\Purchase::class;
    }

    /**
     * 待到货列表
     */

    public function index()
    {
        //是否是超管

        list($limit, $where, $sortArr) = $this->buildTableParames();
        $where = array();
        $where[] = ['a.merge_status', 'in', [4, 5]];
        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        if (isset($filters['union_batch']) && !empty($filters['union_batch'])) {
            $where[] = ['a.union_batch', 'LIKE', "%{$filters['union_batch']}%"];
        }
        if (isset($filters['wl_num']) && !empty($filters['wl_num'])) {
            $where[] = ['b.wl_num', 'LIKE', "%{$filters['wl_num']}%"];
        }
        if (isset($filters['brand']) && !empty($filters['brand'])) {
            $where[] = ['a.brand', 'LIKE', "%{$filters['brand']}%"];
        }
        $list = $this->model
            ->field("a.id,a.brand,SUM(a.real_num) as real_num,SUM(a.real_num_correct) as real_num_correct,a.union_batch,a.admin_id,a.apply_status,a.apply_time,a.product_id,a.seat,a.ddh_time,a.rk_time")
            ->alias('a')
            ->join('qu_dcg b', 'b.union_batch = a.union_batch', 'left')
            ->where($where)
            ->order('a.apply_time desc')
            ->group('a.union_batch')
            ->paginate($limit);

        $lists = $list->items();
        foreach ($lists as $k => $v) {
            $dcg = table('dcg')->where(['union_batch' => $v['union_batch']])->find();
            //查询id
            $day = table('product')
                ->where(['id' => $v['product_id']])->find();
            if (!empty($day)) {
                $sum = $day['arrive_day'];
            } else {
                $sum = 0;
            }

            $lists[$k]['purchase_price'] = !empty($dcg['purchase_price']) ? $dcg['purchase_price'] : 0;
            $lists[$k]['wl_num'] = !empty($dcg['wl_num']) ? $dcg['wl_num'] : 0;
            $lists[$k]['arrive_day'] = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('m'), date('d') + $sum, date('Y')));
            //物流单号
            $batch_info = table('dcg')->where(['union_batch' => $v['union_batch']])->find();
            $lists[$k]['wl_num'] = !empty($batch_info['wl_num']) ? $batch_info['wl_num'] : 0;
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists
        ];
        return json($data);
    }


    /**
     * 导出
     */
    public function export()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $fields = $this->request->get('fields');
        $fields = json_decode($fields, true);

        $header = [];
        foreach ($fields as $vo) {
            $header[] = [$vo['comment'], $vo['field']];
        }

        $tableIds = $this->request->get('tableIds');
        $tableIds = is_array($tableIds) ? $tableIds : explode(',', $tableIds);
        $where[] = ['id', 'in', $tableIds];

        $tableName = $this->model->getName();
        $lists = $this->model
            ->field("id,brand,SUM(`real_num`) as real_num,SUM(`real_num_correct`) as real_num_correct,union_batch,admin_id,apply_status, apply_time,product_id")
            ->where($where)
            ->where(['apply_status' => 4])
            ->order('apply_time desc')
            ->group('union_batch')
            ->limit(100000)
            ->select()
            ->toArray();
        foreach ($lists as $k => $v) {
            $dcg = table('dcg')->where(['union_batch' => $v['union_batch']])->find();
            //查询id
            $day = table('product')
                ->where(['id' => $v['product_id']])->find();
            if (!empty($day)) {
                $sum = $day['arrive_day'];
            } else {
                $sum = 0;
            }

            $lists[$k]['purchase_price'] = !empty($dcg['purchase_price']) ? $dcg['purchase_price'] : 0;
            $lists[$k]['arrive_day'] = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('m'), date('d') + $sum, date('Y')));
        }
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        //查询purchase表的id
        $row['real_num'] = table('purchase')->where(['union_batch' => $row['union_batch']])->sum('real_num');
        $row['real_num'] = (int)$row['real_num'];
        $union_batch = !empty($row['union_batch']) ? $row['union_batch'] : '';
        $purchase_data = table('purchase')->field('id,sku,color,num,real_num,real_num_correct')->where(['union_batch' => $union_batch])->select()->toarray();
        foreach ($purchase_data as $k => $v) {
            $purchase_data[$k]['sku'] = $v['color'] . '-' . $v['sku'];
            $purchase_data[$k]['editname'] = false;
            $purchase_data[$k]['real_num'] = (int)$v['real_num'];
            $purchase_data[$k]['real_num_correct'] = (int)$v['real_num_correct'];
        }
        $row['purchase_data'] = $purchase_data;

        $dcg_info = table('dcg')->where(['union_batch' => $union_batch])->find();
        //物流单号
        if (!empty($dcg_info['wl_num'])) {
            $row['wl_num'] = explode(',', $dcg_info['wl_num']);
        } else {
            $row['wl_num'] = [];
        }

        if ($this->request->isPost()) {
            $post = $this->request->post();
            //更新数据
            if (!empty($post['wl_num'])) {
                $post['wl_num'] = implode(',', $post['wl_num']);
            } else {
                $post['wl_num'] = '';
            }
            $data = [
                'wl_num' => $post['wl_num'],
            ];
            table('dcg')->where(['union_batch' => $post['union_batch']])->update($data);
            //查询该批次号下的数据
            if (!empty($post['purchase_data'])) {
                foreach ($post['purchase_data'] as $k => $value) {
                    if (!empty($value['real_num_correct'] && $value['real_num_correct'] > $value['real_num'] && $value['real_num_correct']  = $value['real_num'])) {
                        table('purchase')->where(['id' => $value['id']])->update(['real_num_correct' => (int)$value['real_num_correct'], 'merge_status' => 6]);
                    }
                }
            }
            try {
                // $this->validate && validate($this->validate)->check($post);
                // $result = $row->save($post);
                // if ($result) {
                return success('保存成功！');
                // }
                // return error('保存失败');
            } catch (ValidateException $e) {

                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }
        return success('ok', $row);
    }


    /**
     * 修改
     *
     */
    public function edit_logistics()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        $union_batch = !empty($row['union_batch']) ? $row['union_batch'] : '';
        $dcg_info = table('dcg')->where(['union_batch' => $union_batch])->find();
        //物流单号
        if (!empty($dcg_info['wl_num'])) {
            $row['wl_num'] = explode(',', $dcg_info['wl_num']);
        } else {
            $row['wl_num'] = [];
        }

        if ($this->request->isPost()) {
            $post = $this->request->post();
            //更新数据
            if (!empty($post['wl_num'])) {
                $post['wl_num'] = implode(',', $post['wl_num']);
            } else {
                $post['wl_num'] = '';
            }
            $data = [
                'wl_num' => $post['wl_num'],
            ];
            table('dcg')->where(['union_batch' => $post['union_batch']])->update($data);
            try {
                return success('保存成功！');
            } catch (ValidateException $e) {
                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }
        return success('ok', $row);
    }

    /**
     * 导出
     */
    public function export_number()
    {
        $id = $this->request->get('id');
        $purchase_info  = table('purchase')->where(['id' => $id])->find();
        $union_batch = !empty($purchase_info['union_batch']) ? $purchase_info['union_batch'] : '';
        $lists = array();
        if (!empty($union_batch)) {
            $lists = table('purchase')->field('id,sku,color,num,real_num,real_num_correct,brand')->where(['union_batch' => $union_batch])->select()->toarray();
        }
        $real_num = 0;
        $num = 0;
        foreach ($lists as $k => $v) {
            $lists[$k]['union_batch'] = $union_batch;
            $lists[$k]['sku'] = $v['color'] . '-' . $v['sku'];
            $real_num += $v['real_num'];
            $num += $v['real_num_correct'];
        }
        $num1 = [];
        $num1['id'] = '总计';
        $num1['union_batch'] = '';
        $num1['sku'] = '';
        $num1['real_num_correct'] = $num;
        $num1['brand'] = '';
        $num1['real_num'] = $real_num;
        $lists[] = $num1;
        $tableName = $this->model->getName();

        $header = array();
        $header[] = ['ID', 'id'];
        $header[] = ['批次号', 'union_batch'];
        $header[] = ['编号', 'brand'];
        $header[] = ['SKU', 'sku'];
        $header[] = ['待到货数', 'real_num'];
        $header[] = ['实际到货数', 'real_num_correct'];

        $fileName = "export_" . $tableName . "_" . time();
        // halt($header);
        return Excel::exportData($lists, $header, $fileName, 'xls');
    }
    /**
     * 上传文件
     */
    public function uploads()
    {
        $file = $this->request->file('file');
        // try {
        $upload = new Upload();
        $res = $upload->upload($file);
        if ($res['url']) {
            // return success('ok', $res['url']);
            $return = $this->import_cost($res['url']);
            return success('ok', $return);
        } else {
            return error($res['msg']);
        }
        // } catch (\Exception $e) {
        //     Log::error("---ajax---upload--error:" . $e);
        // }
        return error('上传文件失败');
    }
    //导入花费
    public function import_cost($url)
    {
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1]);
        unset($data[1]);
        foreach ($data as  $value) {
            if (isset($value[0]) && !empty($value[0]) && isset($value[5])) {
                $purchase = array();
                $purchase['real_num'] = $value[5];
                table('purchase')
                    ->where('id', $value[0])
                    ->update($purchase);
            }
        }
        return $url;
    }
}
